unit UnitK;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ExtCtrls, Math;

const
  N = 9;
  R = 20;
  D = 4;

type
  TForm1 = class(TForm)
    Image1: TImage;
    BitBtn1: TBitBtn;
    procedure BitBtn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  k, l, x, y, x0, y0, m, p, q: Integer;

implementation

{$R *.dfm}

procedure TForm1.BitBtn1Click(Sender: TObject);
var
  i, j: Integer;
begin
  p:=Floor(Log2(N));
  if (p*(1 + p) div 2) = N then
  begin
    if p <> Log2(N) then
    begin
      k:= p + 1;
    end else begin
      k:= p;
    end;
  end else begin
    q:= N - (p*(1 + p) div 2);
    while q <> 0 do
    begin
      if q = N - ((p + 1)*(2 + p) div 2) then
      begin
        p:=p+1;
      end;
      q:=q-1;
    end;
    k:=p;
  end;
  l:= N - (((k+1)*k) div 2);
  m:=k;
  x0:= 200 + k*(R+D);
  y0:= k*(R+D) + 100;
  for i:= 1 to k+1 do
  begin
    if i = 1 then
    begin
      for j:= 1 to l do
      begin
        x:= x0 - (2*R+D)*(k-l+j) - R;
        y:= y0 + 2*R;
        Image1.Canvas.Ellipse(x+R, y+R, x-R, y-R);
      end;
      x:=x0;
      y:=y0;
    end else begin
      for j:= 1 to m do
      begin
        x:=x-(2*R+D);
        Image1.Canvas.Ellipse(x+R, y+R, x-R, y-R);
      end;
      Dec(m);
      x:= x0 - R*(i-1) - (D div 2)*(i-1);
      y:= y - 2*R;
    end;
  end;
end;

end.
